/**
 * @format
 * @Author: TC
 * @Date: 2021-09-27 15:15:38
 * @Last Modified by: TC
 * @Last Modified time: 2025-06-19 19:08:08
 */

import { BufferAsset } from "cc";
import { nsBundleConst } from "../../Script/Const/BundleConst";
import { app } from "../App";
import { SingleBase } from "../Interface/SingleBase";
import { ASSERT_TYPE } from "../Module/Res/ResConst";
import { BinFileData } from "../Util/BinUtility";

//声音管理类
export class ConfigManager extends SingleBase {
    private _mapCfg: Map<string, any> = new Map();

    public static get instance(): ConfigManager {
        return this._instance ? (this._instance as ConfigManager) : (this._instance = new ConfigManager());
    }

    constructor() {
        super();
    }

    public loadCfgBin(cbComplete: () => void): void {
        app.resMgr.loadBin(nsBundleConst.Config, "jsonCfg", (bin: BufferAsset) => {
            app.bin.parseBin(bin, (binDataList: BinFileData[]) => {
                app.resMgr.getBundle(nsBundleConst.Config).releaseAll();
                this.praseAllCfgToJson(binDataList, cbComplete);
            });
        });
    }

    /**
     * 将解压数据解析为json
     * @param binDataList
     * @param cb
     */
    private praseAllCfgToJson(binDataList: BinFileData[], cb: () => void): void {
        binDataList.forEach((data) => {
            let jsonData = JSON.parse(data.text);
            this._mapCfg.set(data.name, jsonData);
        });
        cb();
    }

    /**
     * 根据表名获取整个配置表信息
     * @param jsonName
     * @returns
     */
    public getCfg(jsonName: string): any[] {
        let cfgData = this._mapCfg.get(jsonName);
        let titleList: string[] = cfgData.title;
        let contentList: any[][] = cfgData.content;
        let list = [];
        contentList.forEach((content) => {
            let data = {};
            titleList.forEach((key, index) => {
                data[key] = content[index];
            });
            list.push(data);
        });
        return list || [];
    }

    /**
     * 根据某个键值获取一条配置数据
     * @param jsonName
     * @param key
     * @param val
     */
    public getCfgByKey(jsonName: string, key: string, val: number | string): any {
        let list = this.getCfg(jsonName);
        let data = null;
        for (let i = 0, len = list.length; i < len; i++) {
            if (list[i][key] == val) {
                data = list[i];
            }
        }
        if (!data) {
            app.log.error("getCfgByKey err", jsonName, key, val);
        }
        return data;
    }
}
